<!-- 登录界面 -->
<template>
    <div class="shell">
        <!-- 顶部关闭按钮，通过ipc进程监控控制 -->
        <div class="menu">
            <CloseBold @click="closeApp" class="close-icon" />
        </div>
        <!-- 顶部logo区域 -->
        <div class="top">
            <div class="logo">
                <img src="@/assets/CodeRealm.png" />
            </div>
            <div class="l-name">
                <span>CodeRealm</span><sup>®</sup>
            </div>
            <!-- 临时身份区分下拉列表 -->
            <!-- <div class="r-top">
                <el-select v-model="identity" placeholder="请选择身份" style="width: 140px;margin-left: 20px">
                    <el-option label="用户" value="1" />
                    <el-option label="开发者" value="2" />
                    <el-option label="管理员" value="3" />
                </el-select>
            </div> -->
        </div>
        <!-- 中部内容区域 -->
        <div class="middle">
            <!-- 左侧表单 -->
            <div class="m-left">
                <div class="inp">
                    <span style="color: #1999FF" class="label">用账户名称登录</span>
                    <input v-model="Form.username" spellcheck="false" type="text">
                    <!-- 发现steam竟然没关掉默认的拼写检测，这默认的功能是很鸡肋的，会出现红色波浪线 -->
                </div>
                <div class="inp">
                    <span class="label">密码</span>
                    <input v-model="Form.password" type="password" @keyup.enter="login">
                </div>
                <div class="memory" @click="keepAccount">
                    <Select class="sel-icon" :class="{ white: memory }" />
                    <span>记住我</span>
                </div>
                <div class="bnt">
                    <button @click="login" :disabled="isSubmitting">{{ isSubmitting ? '登录中...' : '登录' }}</button>
                </div>
            </div>
            <!-- 右侧二维码 -->
            <div class="m-right">
                <img src="@/assets/qrcode.png" alt="">
                <span class="r-bottom">通过二维码浏获取 CodeRealm 网站</span>
            </div>
        </div>
        <!-- 底部跳转 -->
        <div class="bottom">
            <div>
                <span>还没有 CodeRealm 账户？</span>
                <span style="margin-left: 6px;cursor: pointer;" class="underline" @click="toReg">创建免费账户</span>
            </div>
        </div>
    </div>
</template>

<script>
// 引入element的加载动画
import { ElLoading } from 'element-plus'
export default {
    data() {
        return {
            memory: localStorage.getItem('memory') === 'true',
            Form: {
                username: '',
                password: '',
            },
            isSubmitting: false, // 防抖标志，防止重复提交
        }
    },
    methods: {
        keepAccount() {
            console.log(this.memory)
            this.memory = !this.memory
            localStorage.setItem('memory', this.memory)
            
            // 如果选择记住账户，则保存当前输入的账户和密码
            if (this.memory && this.Form.username) {
                const userSecret = {
                    account: this.Form.username,
                    pwd: this.Form.password
                }
                localStorage.setItem('userSecret', JSON.stringify(userSecret))
            } else {
                // 如果取消记住账户，则清除保存的账户信息
                localStorage.removeItem('userSecret')
            } 
        },
        // 页面跳转函数
        toReg() {
            this.$router.push('/reg')
        },
        // 登录函数
        async login() {
            // 防止重复提交
            if (this.isSubmitting) {
                return
            }
            
            // 表单验证
            if (!this.Form.username || !this.Form.password) {
                return this.$tools.alertMsg('账号或密码不能为空', 'error');
            }
            
            this.isSubmitting = true;
            const that = this;
            
            const query = {
                mname: that.Form.username,
                pwd: that.Form.password,
            };
            
            const loadingInstance = ElLoading.service({
                text: '登录中...',
                background: 'rgba(23,29,37,0.7)'
            });
            
            try {
                const response = await that.$axios.post('login', query);
                console.log(response)
                if (response.status !== 200) {
                    that.$tools.alertMsg('系统错误', 'error');
                    return;
                }
                
                if (response.data.code === 200) {
                    // 如果选择记住账户，则保存当前登录的账户和密码
                    if (that.memory) {
                        const userSecret = {
                            account: that.Form.username,
                            pwd: that.Form.password
                        };
                        localStorage.setItem('userSecret', JSON.stringify(userSecret));
                    }
                    
                    localStorage.setItem('token', response.data.data.token);
                    that.$store.commit('saveUserInfo', response.data.data.user)
                    // console.log(response.data.data.user)
                    const identity = response.data.data.user.level
                    // 根据身份设置默认页面路由
                    let targetRoute = '/home';
                    if (identity === 0) {
                        that.$store.commit('changeView', 2);
                        targetRoute = '/home/library';
                    } else if (identity == 1) {
                        that.$store.commit('changeView', 1);
                        targetRoute = '/home/gamemanager';
                    } else if (identity == 2) {
                        that.$store.commit('changeView', 1);
                        targetRoute = '/home/examine';
                    }
                    that.$tools.alertMsg('登录成功，即将进入首页', 'success');
                    
                    setTimeout(() => { 
                        that.$router.push(targetRoute);
                        that.isSubmitting = false;
                    }, 1000);
                } else {
                    that.$tools.alertMsg(response.data.message, 'error', 1500);
                    that.isSubmitting = false;
                }
            } catch (error) {
                console.error('登录错误:', error);
                that.$tools.alertMsg('登录失败，请稍后重试', 'error', 1500);
                that.isSubmitting = false;
            } finally {
                loadingInstance.close();
            }
        },
        // ipc通信关闭应用
        closeApp() {
            this.$ipc.sendSync('operateMenu', 'close')
        }
    },
    // 页面渲染前获得数据
    created() {
        if (this.memory) {
            try {
                const secret = JSON.parse(localStorage.getItem('userSecret') || '{}');
                this.Form.username = secret.account || '';
                this.Form.password = secret.pwd || '';
            } catch (error) {
                console.error('解析保存的账户信息失败:', error);
                localStorage.removeItem('userSecret'); // 清除可能损坏的数据
            }
        }
        // this.getDeviceLocation();
    },
    mounted(){
        // this.getDeviceLocation();
    }
}
</script>

<style lang="less" scoped>
.white {
    color: #ffffff !important;
}

.underline {
    text-decoration: underline;
}

.shell {
    padding: 0px 40px 30px 0px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #212328;
    // 控制菜单
    .menu {
        text-align: right;
        margin-right: -40px;
        -webkit-app-region: drag;

        .close-icon {
            -webkit-app-region: no-drag;
            cursor: pointer;
            width: 17px;
            height: 17px;
            padding: 8px;
            color: #788A92;

            &:hover {
                background-color: red;
                color: #E0E1E6;
            }
        }
    }

    .top,
    .middle,
    .bottom {
        padding-left: 40px;
    }
    // 顶部样式
    .top {
        display: flex;
        align-items: center;
        color: #E0E1E6;
        margin-bottom: 6px;

        .logo {
            img {
                width: 44px;
                height: 44px;
            }
        }

        .l-name {
            background: linear-gradient(to right bottom, #3A3DDC, #26BCDC);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin-left: 4px;

            span {
                font-size: 24px;
                font-weight: bold;
                letter-spacing: 2px;
            }

            sup {
                font-size: 9px;
                vertical-align: top;
            }
        }
    }
    // 中部样式
    .middle {
        display: flex;
        justify-content: space-between;

        .m-left,
        .m-right {
            display: flex;
            flex-direction: column;
        }

        .m-left {
            .inp {
                text-align: left;
                display: flex;
                flex-direction: column;
                margin-top: 11px;

                .label {
                    font-size: 12px;
                    color: #AFAFAF;
                    margin-bottom: 3px;
                }

                input {
                    background-color: #32353C;
                    width: 384px;
                    height: 38px;
                    border-radius: 2px;
                    color: #E0E1E6;
                    outline: none;
                    border: none;
                    text-indent: 10px;
                    font-size: 14px;

                    &:hover {
                        background-color: #393C44;
                    }
                }
            }

            .memory {
                margin-top: 10px;
                display: flex;
                align-items: center;
                cursor: pointer;
                user-select: none;

                span {
                    vertical-align: middle;
                    font-size: 12px;
                    color: #AFAFAF;
                }

                .sel-icon {
                    margin-right: 6px;
                    width: 15px;
                    height: 15px;
                    padding: 2px;
                    color: #32353C;
                    background-color: #32353C;
                    border-radius: 2px;
                }

                &:hover .sel-icon {
                    background-color: #393C44;
                    color: #393C44;
                }
            }

            .bnt {
                margin-top: 12px;

                button {
                    cursor: pointer;
                    width: 100%;
                    height: 44px;
                    color: #fff;
                    border: none;
                    outline: none;
                    font-size: 15px;
                    border-radius: 2px;
                    background-image: linear-gradient(to right, #06BFFF, #2D73FF);

                    &:hover {
                        background-image: linear-gradient(to right, #06BFFF, #08BAFF 30%, #2D73FF);
                    }
                }

            }
        }

        .m-right {
            display: flex;
            flex-direction: column;
            text-align: left;

            span {
                font-size: 12px;
                color: #AFAFAF;
            }

            .r-top {
                color: #1999FF;
            }

            img {
                width: 200px;
                height: 200px;
                border-radius: 10px;
                margin: 2px 0px 8px 0px;
            }
        }
    }
    // 底部样式
    .bottom {
        padding-top: 30px;
        font-size: 12px;
        color: #AFAFAF;
        display: flex;
        justify-content: space-between;
    }
}</style>